package cn.zmwh.bbs.modules.bbs.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.zmwh.bbs.enums.ArticleStatusEnum;
import cn.zmwh.bbs.modules.bbs.pojo.entity.ForumArticle;
import cn.zmwh.bbs.modules.bbs.pojo.entity.ForumArticleAttachment;
import cn.zmwh.bbs.modules.bbs.pojo.request.ListRequest;
import cn.zmwh.bbs.modules.bbs.pojo.request.PublishRequest;
import cn.zmwh.bbs.modules.bbs.pojo.vo.ForumArticleVO;
import cn.zmwh.bbs.modules.bbs.service.ForumArticleService;
import cn.zmwh.common.core.api.PageEntity;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.constants.Constants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 文章信息 前端控制器
 * </p>
 *
 * @author dmzmwh
 * @since 2025-07-18
 */
@RestController
@RequestMapping("bbs/forum/article")
public class ForumArticleController {

    @Autowired
    private ForumArticleService forumArticleService;

    @PostMapping("/publish")
    @ApiOperation(value = "发布文章")
    public Result publish(@RequestBody PublishRequest request, HttpServletRequest httpServletRequest) {

        return forumArticleService.publish(request, httpServletRequest);
    }

    @PostMapping("/list")
    public Result<PageEntity<ForumArticle>> list(@RequestBody ListRequest request) {
        LambdaQueryWrapper<ForumArticle> wrapper = Wrappers.<ForumArticle>lambdaQuery()
                .eq(request.getBoardId() != null, ForumArticle::getBoardId, request.getBoardId())
                .eq(request.getPBoardId() != null, ForumArticle::getPBoardId, request.getPBoardId())
                .eq(ForumArticle::getStatus, ArticleStatusEnum.AUDITED.getStatus());

        IPage<ForumArticle> page = forumArticleService.page(request, wrapper);

        Result<PageEntity<ForumArticle>> pageEntityResult = Result.pageOk(page.getRecords(), page.getTotal());
        return pageEntityResult;
    }


    @GetMapping("/detail")
    public Result<ForumArticleVO> detail(@ApiIgnore @RequestHeader(Constants.UID) Long uid, String id) {

        return forumArticleService.detail(uid,id);
    }


//
//
//    @RequestMapping("/loadBoard4Post")
//    @GlobalInterceptor(checkLogin = true)
//    public ResponseVO loadBoard4Post(HttpSession session) {
//        SessionWebUserDto userDto = getUserInfoFromSession(session);
//        Integer postType = null;
//        if (!userDto.getAdmin()) {
//            postType = 1;
//        }
//        return getSuccessResponseVO(forumBoardService.getBoardTree(postType));
//    }
//
//
//    @RequestMapping("/doLike")
//    @GlobalInterceptor(checkLogin = true, checkParams = true, frequencyType = UserOperFrequencyTypeEnum.DO_LIKE)
//    public ResponseVO doLike(HttpSession session, @VerifyParam(required = true) String articleId) {
//        SessionWebUserDto userDto = getUserInfoFromSession(session);
//        likeRecordService.doLike(articleId, userDto.getUserId(), userDto.getNickName(), OperRecordOpTypeEnum.ARTICLE_LIKE);
//        return getSuccessResponseVO(null);
//    }
//
//    @RequestMapping("/getUserDownloadInfo")
//    @GlobalInterceptor(checkLogin = true, checkParams = true)
//    public ResponseVO getUserDownloadInfo(HttpSession session, @VerifyParam(required = true) String fileId) {
//        UserInfo userInfo = userInfoService.getUserInfoByUserId(getUserInfoFromSession(session).getUserId());
//        Map<String, Object> result = new HashMap();
//        result.put("userIntegral", userInfo.getCurrentIntegral());
//        ForumArticleAttachmentDownload attachmentDownload = forumArticleAttachmentDownloadService.getForumArticleAttachmentDownloadByFileIdAndUserId(fileId,
//                getUserInfoFromSession(session).getUserId());
//        result.put("haveDownload", attachmentDownload != null);
//        return getSuccessResponseVO(result);
//    }
//
//    @RequestMapping("/attachmentDownload")
//    @GlobalInterceptor(checkLogin = true, checkParams = true)
//    public void attachmentDownload(HttpSession session, HttpServletRequest request, HttpServletResponse response,
//                                   @VerifyParam(required = true) String fileId) {
//        ForumArticleAttachment attachment = forumArticleAttachmentService.downloadAttachment(fileId, getUserInfoFromSession(session));
//        InputStream in = null;
//        OutputStream out = null;
//        String downloadFileName = attachment.getFileName();
//        String filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_ATTACHMENT + attachment.getFilePath();
//        File file = new File(filePath);
//        try {
//            in = new FileInputStream(file);
//            out = response.getOutputStream();
//            response.setContentType("application/x-msdownload; charset=UTF-8");
//            // 解决中文文件名乱码问题
//            if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {//IE浏览器
//                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
//            } else {
//                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1");
//            }
//            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
//            byte[] byteData = new byte[1024];
//            int len = 0;
//            while ((len = in.read(byteData)) != -1) {
//                out.write(byteData, 0, len); // write
//            }
//            out.flush();
//        } catch (Exception e) {
//            logger.error("下载异常", e);
//            throw new BusinessException("下载失败");
//        } finally {
//            try {
//                if (in != null) {
//                    in.close();
//                }
//
//            } catch (IOException e) {
//                logger.error("IO异常", e);
//            }
//            try {
//                if (out != null) {
//                    out.close();
//                }
//
//            } catch (IOException e) {
//                logger.error("IO异常", e);
//            }
//        }
//    }
//
//
//    @RequestMapping("/articleDetail4Update")
//    @GlobalInterceptor(checkLogin = true, checkParams = true)
//    public ResponseVO articleDetail4Update(HttpSession session, @VerifyParam(required = true) String articleId) {
//        SessionWebUserDto userDto = getUserInfoFromSession(session);
//        ForumArticle forumArticle = forumArticleService.getForumArticleByArticleId(articleId);
//        if (forumArticle == null || !forumArticle.getUserId().equals(userDto.getUserId())) {
//            throw new BusinessException("文章不存在或你无权编辑该文章");
//        }
//        FormArticleUpdateDetailVO detailVO = new FormArticleUpdateDetailVO();
//        detailVO.setForumArticle(forumArticle);
//        if (forumArticle.getAttachmentType() == 1) {
//            ForumArticleAttachmentQuery articleAttachmentQuery = new ForumArticleAttachmentQuery();
//            articleAttachmentQuery.setArticleId(forumArticle.getArticleId());
//            List<ForumArticleAttachment> forumArticleAttachmentList = forumArticleAttachmentService.findListByParam(articleAttachmentQuery);
//            if (!forumArticleAttachmentList.isEmpty()) {
//                detailVO.setAttachment(CopyTools.copy(forumArticleAttachmentList.get(0), ForumArticleAttachmentVo.class));
//            }
//        }
//        return getSuccessResponseVO(detailVO);
//    }
//
//    /**
//     * 搜索
//     *
//     * @param keyword
//     * @return
//     */
//    @RequestMapping("/search")
//    @GlobalInterceptor(checkParams = true)
//    public ResponseVO updateArticle(@VerifyParam(required = true, min = 3) String keyword) {
//        ForumArticleQuery query = new ForumArticleQuery();
//        query.setTitleFuzzy(keyword);
//        PaginationResultVO result = forumArticleService.findListByPage(query);
//        return getSuccessResponseVO(result);
//    }
}

